﻿using Microsoft.EntityFrameworkCore;
using TuLing.Blazor.Dto;
using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public class ProductService: BaseService
    {
        public ProductService(DefaultDbContext context) : base(context) { }

        /// <summary>
        /// 商品列表
        /// </summary> 
        public List<Product> Search(BaseInput input)
        {
            if (input.keyword == null)
            {
                return _context.Products.AsNoTracking().ToList();
            }
            return _context.Products.AsNoTracking().Where(m =>
                m.Code.Contains(input.keyword) ||
                m.Name.Contains(input.keyword)).ToList();
        }
        
        public Product? Get(long id)
        {
            return _context.Products.AsNoTracking().FirstOrDefault(m => m.Id == id);
        }

        /// <summary>
        /// 保存商品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public void Save(Product input)
        {            
            var exist = _context.Products.Any(m => m.Name == input.Name && m.Id != input.Id);

            // 检查商品名称是否存在
            if (exist)
            {
                throw new Exception("商品名已存在，请检查！");
            }
            else
            {
                // 检查商品编码是否存在                
                if (input.Id == 0)
                {
                    _context.Products.Add(input);
                }
                _context.SaveChanges();
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>  
        public void Delete(long id)
        {
            var pType = _context.Products.First(m => m.Id == id);
            _context.Products.Remove(pType);
            _context.SaveChanges();
        }

    }
}
